package com.qiandw.utils;

import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

/**
 * @author coxx
 */
public class IPUtils {

    private static final String UNKNOWN = "unknown";

    public static String getIPAddress(ServerHttpRequest httpRequest){
        HttpHeaders httpHeaders = httpRequest.getHeaders();
        String ip = Optional.ofNullable(httpHeaders.getFirst("x-forwarded-for")).orElse("unknown");
        if(UNKNOWN.equalsIgnoreCase(ip)){
            ip = Optional.ofNullable(httpHeaders.getFirst("Proxy-Client-IP")).orElse("unknown");
        }
        if (UNKNOWN.equalsIgnoreCase(ip)) {
            ip = Optional.ofNullable(httpHeaders.getFirst("WL-Proxy-Client-IP")).orElse("unknown");
        }
        if (UNKNOWN.equalsIgnoreCase(ip)) {
            ip = Optional.ofNullable(httpHeaders.getFirst("HTTP_CLIENT_IP")).orElse("unknown");
        }
        if (UNKNOWN.equalsIgnoreCase(ip)) {
            ip = Optional.ofNullable(httpHeaders.getFirst("HTTP_X_FORWARDED_FOR")).orElse("unknown");
        }
        if (UNKNOWN.equalsIgnoreCase(ip)) {
            ip = Optional.ofNullable(httpRequest.getRemoteAddress().getAddress().getHostAddress()).orElse("unknown");
        }
        return ip;
    }

    public static String getIPAddress(HttpServletRequest httpRequest){
        String ip = httpRequest.getHeader("x-forwarded-for");
        if(ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)){
            ip = httpRequest.getHeader("Proxy-Client-IP");
        }
        if (ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = httpRequest.getHeader("WL-Proxy-Client-IP");
        }
        if (ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = httpRequest.getHeader("HTTP_CLIENT_IP");
        }
        if (ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = httpRequest.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = httpRequest.getRemoteAddr();
        }
        return ip;
    }
}
